<?php

$log_config = parse_ini_file('./log.ini',true);
$table_config = parse_ini_file('./table.ini',true);

$all_api = array_keys($table_config);
unset($all_api['common']);
$all_platform = $log_config['platform'];
$all_game = $log_config['game'];

if(isset($_GET['search'])){
	$param = $_GET;
	if(!isset($param['page'])){
		$param['page'] = 1;
	}
	$game_id = $_GET['game_id'];
	
	$date_dir = date("Y/m",strtotime($param['end_time']))."/*/";
	$param['begin_time'] = strtotime($param['begin_time']);
	$param['end_time'] = strtotime($param['end_time']." 23:59:59");
	$param['log_path'] = $log_config['log']['path']."/%s/%s/%s/%s";
	$param['log_path'] = sprintf($param['log_path'],$log_config['game'][$game_id],$log_config['platform'][$game_id],$param['server_id'],$date_dir);
	$param['per_page'] = 100;
 
	list($log_data,$total_num)= get_log($param,$table_config);
	//var_dump(count($log_data));
	$page_str = Page::get_str($param['page'],$total_num,$param['per_page']);
	
	$config_field = $table_config['common']+$table_config[$param['api']];
	unset($config_field['log_time']);
	unset($config_field['api']);
	// echo "<pre>";
	// print_r($log_data);
	
}



function get_where($param){
    $where = array();
    $where_str = "";
	 if(isset($param['role_id']) && $param['role_id']){
        $where[] = "$5=={$param['role_id']}";
    }
	
    if(!empty($where)){
        $where_str = " && ".implode(" && ",$where);
    }
    return $where_str;
}

/**
 *
 * @param $param
 */
//http://log.bajian.wan.sogou.com/index.php?a=get_ingot_expend_log&server_id=10001
function get_log($param,$table_config){

    $where_str = get_where($param);
    //登录时间，角色id，角色等级，平台id，区服id，战力，登录ip,
    $cmd = <<<EOT
cat {$param['log_path']}/{$param['api']}[0-9]*.txt |awk -F" " '{print $3}'|awk -F"," '{if($7>=%s && $7<=%s %s){print $0}else{}}'
EOT;
    $cmd = sprintf($cmd,$param['begin_time'],$param['end_time'],$where_str);

    $data = exec_cmd($cmd,$param);

    $log = array();
	$table_field = array_keys($table_config[$param['api']]);
    foreach($data['data'] as $k=>$v){
        $log_arr = explode(",",$v);
		$log_data = array(
			'gid'=>$log_arr[0],
			'sid'=>$log_arr[1],
			'oldsid'=>$log_arr[2],
			'user_id'=>$log_arr[3],
			'role_id'=>$log_arr[4],
			'part_id'=>$log_arr[5],
			'time'=>date("Y-m-d H:i:s",$log_arr[6]),
		);
		foreach($table_field as $k=>$v){
			$table_index = $k+7;
			$log_data[$v] = $log_arr[$table_index];
		}
		
        $log[] = $log_data;
    }
    
	return array($log,$data['total']);
}

/***
 * 执行shell 并返回结果
 * @param $cmd
 * @param $param
 * @return array
 */
function exec_cmd($cmd,$param){
    exec($cmd,$res);
	if(isset($_GET['debug'])){
		echo $cmd;
	}

    $res = array_reverse($res);
    $total = count($res);
    $total_page = ceil($total/$param['per_page']);
    $offset = $param['page']-1;
	if($param['per_page']<$total){
		  $data = array_slice($res,$offset*$param['per_page'],$param['per_page']);
	}else{
		$data = $res;
	}
  
    $res = array(
        'total'=>$total,
        'per_page'=>$param['per_page'],
        'total_page'=>$total_page,
        'page'=>$param['page'],
        'data'=>$data,
    );
    return $res;
}

?>
<form>
<input type="hidden" name="search" value="1">
<input type="hidden" name="page" value="<?php if(isset($_GET['page'])){echo $_GET['page'];}else{echo 1;}?>">
<label class="control-label">平台：</label>
<select class="form-control" name="platform" id="platform">
	<option value="" selected="">选择平台</option>
	<?php foreach($all_platform as $k=>$v){ ?>
	<option value="<?=$v?>" <?php if(isset($_GET['platform']) && $v==$_GET['platform']){echo "selected";}?>><?=$v?></option>
	<?php }?>
	</select>
	
<label class="control-label">游戏：</label>
<select class="form-control" name="game_id" id="game_id">
	<option value="" selected="">请选择</option>
	<?php foreach($all_game as $k=>$v){ ?>
	<option value="<?=$k?>" <?php if(isset($_GET['game_id']) && $k==$_GET['game_id']){echo "selected";}?>><?=$v?></option>
	<?php }?>
	</select>	
<label class="control-label">api：</label>
<select class="form-control" name="api" id="api">
	<option value="" selected="">请选择</option>
	<?php foreach($all_api as $k=>$v){ ?>
	<option value="<?=$v?>" <?php if(isset($_GET['api']) && $v==$_GET['api']){echo "selected";}?>><?=$v?></option>
	<?php }?>
	</select>
	
<label class="control-label">区服：</label>
<input class="form-control" type="text" name="server_id" id="server_id" value="<?php if(isset($_GET['server_id'])){echo $_GET['server_id'];}?>">
<label class="control-label">角色ID：</label>
<input class="form-control" type="text" name="role_id" id="role_id" value="<?php if(isset($_GET['role_id'])){echo $_GET['role_id'];}?>">



<label class="control-label">时间：</label>
<span class="date-range">
<input placeholder="开始时间" class="form-control date-range00 date-ico" type="text" name="begin_time" id="begin_time" value="2018-03-01">
<input placeholder="结束时间" class="form-control date-range01 date-ico" type="text" name="end_time" id="end_time" value="2018-04-08">
</span>

<button class="btn btn-info m-l" type="submit"> 查询</button>
</form>
<style>
table
  {
  border-collapse:collapse;
  }

table,th, td
  {
  border: 1px solid black;
  }
  .pages a{
	  margin:5px;
  }
</style>
<?php if(isset($_GET['search'])) {?>
<table>
<tr>
<?php foreach($config_field as $k=>$v){?>
<td><?=$v?></td>
<?php }?>
</tr>

<?php foreach($log_data as $k=>$v){?>
<tr>
<?php $v = array_map(function($n){
		return "<td>{$n}</td>";
},$v);
echo implode("",$v);
?>
</tr>
<?php }?>




</table>

<?=$page_str?>
<?php }?>

<?php 

class Page{
    private $_current_page; //当前页
    private $_current_url; //当前URL
    private $_total_num; //总记录数
    private $_pagesize = 10; //每页显示数目
    private $_pagelen = 5; //页面显示数目(长度)
    private $_pageclass = 'pages'; //所用分页样式类名
    private $_pagestring; //分页HTML字符串
    private $_total_pages; //总页数
    private $_pageoffset = 3; //页数偏移量
    public $total_num_str= '<span class="rows">共 %s条记录</span>';
    public $next_page  = '&gt;';
    public $last_page  = '&gt;&gt;';
    public $prev_page  = '&lt;';
    public $first_page = '&lt;&lt;';
    private  static $page_instance=null;
    public static function get_str($page,$total_num,$page_size=10,$current_url=''){
        if(!self::$page_instance){
            self::$page_instance = new self();
        }
        self::$page_instance ->setCurrentPage($page);
        self::$page_instance ->setTotalNum($total_num);
        self::$page_instance ->setPageSize($page_size);
        self::$page_instance ->setCurrentUrl();
        return self::$page_instance->output();
    }

    public function setCurrentPage($page) {
        $this->_current_page = intval($page);
    }
    public function setTotalNum($num) {
        $this->_total_num = intval($num);
    }
    public function setPageSize($pagesize) {
        $this->_pagesize = intval($pagesize);
    }
    public function setCurrentUrl($current_url='') {
        if ( ! $current_url) {
            $current_url = $_SERVER["REQUEST_URI"];
            $parse_url   = parse_url($current_url);

            if ( isset($parse_url["query"]) ) {
                $current_url = preg_replace('/page=[^&]*/',"page=%s",$current_url);

            } else {
                $current_url.="?page=%s";
            }
            $this->_current_url = $current_url;
        } else {
            $this->_current_url = rtrim($current_url, '/') . '/';
        }
    }
    public function output() {
        if ( ! $this->_current_url ) {
            $this->setCurrentUrl();
        }
        
        $this->_caculateParam();
        $this->_buildOutput();
        return $this->_pagestring;
    }
    private function _caculateParam() {
        if (!$this->_total_num) return array();
        $this->_total_pages = ceil($this->_total_num / $this->_pagesize);
        $this->_current_page < 1 && $this->_current_page = 1;
        $this->_current_page > $this->_total_pages && $this->_current_page = $this->_total_pages;
        //Make sure _pagelen is odd number.
        $this->_pagelen = $this->_pagelen % 2 ? $this->_pagelen : $this->_pagelen + 1;
        $this->_pageoffset = ($this->_pagelen - 1) / 2;
    }
    private function _buildOutput() {
        $this->_pagestring  = '';
        $this->_pagestring .= $this->_pageclass ? '<div class="' . $this->_pageclass . '">' : '<div>';
        $this->_pagestring.= sprintf($this->total_num_str,$this->_total_num);
        $this->_buildOutputPageList();
        $this->_pagestring .= '&nbsp;&nbsp;';
        $this->_pagestring .= '</div>';
    }
    private function _buildOutputPageList() {
        $pagemin = 1;
        $pagemax = $this->_total_pages;
        
        if( $this->_current_page != 1 ) {
            $prev = $this->_current_page-1 > 1 ? $this->_current_page-1 : 1;
            $this->_pagestring .= "<a href='".$this->getPageUrl(1)."'>".$this->first_page."</a>
            <a href='".$this->getPageUrl($prev)."'>".$this->prev_page."</a>";
        } else {
            $this->_pagestring .= "<a href=\"javascript:;\">".$this->first_page."</a>
            <a href=\"javascript:;\">".$this->prev_page."</a>";
        }
        
        //Ensure page offset number
        if($this->_total_pages > $this->_pagelen){
            if ($this->_current_page <= $this->_pageoffset) {
                $pagemin = 1;
                $pagemax = $this->_pagelen;
            } else {
                if($this->_current_page + $this->_pageoffset >= $this->_total_pages + 1){
                    $pagemin = $this->_total_pages - $this->_pagelen + 1;
                    $pagemax = $this->_total_pages;
                } else {
                    $pagemin = $this->_current_page - $this->_pageoffset;
                    $pagemax = $this->_current_page + $this->_pageoffset;
                }
            }
        }
        for($i = $pagemin; $i <= $pagemax; $i++){
            if($i == $this->_current_page){
                $this->_pagestring .= "<span class=\"current\">{$i}</span>"; //
            } else {
                $this->_pagestring .= "<a href='".$this->getPageUrl($i)."'>".$i."</a>";
            }
        }
        if( $this->_current_page != $this->_total_pages){
            $next = $this->_current_page+1 > $this->_total_pages ? $this->_total_pages : $this->_current_page+1;
            $this->_pagestring .= "<a href='".$this->getPageUrl($next)."'>".$this->next_page."</a>";
            $this->_pagestring .= "<a href='".$this->getPageUrl($this->_total_pages)."'>".$this->last_page."</a>";
        } else {
            $this->_pagestring .= "
                <a href=\"javascript:;\">".$this->next_page."</a>
                <a href=\"javascript:;\">".$this->last_page."</a>";
        }

    }

    public function getPageUrl($page){
        $url =  sprintf($this->_current_url,$page);
        return $url;
    }
}
